const uuid = require("uuid");
const axios = require("axios").default.create({
  headers: {
    "User-Agent": "okhttp/3.10.0"
  },
  maxContentLength:Number.MAX_SAFE_INTEGER
});
const CommonAxerrHandlerGen = require("./CommonAxerrHandler")
const TokenGetter = require("./TokenGetter").TokenGetter
const Toolbox = require("./Toolbox");
const randomstring = require("randomstring");
const random_number = require("random-number");
const path = require("path");
const url = require("url");
const util = require("util");
const fs = require("fs");
const FormData = require("form-data")

class StaticFormUploader {


  /**
   * 
   * @param {String} upload_qiniu_host 
   */
  constructor(upload_qiniu_host = "http://upload.qiniup.com") {
    this.UPLOAD_QINIU_HOST = upload_qiniu_host;
  }


  /**
   * @returns {FormData}
   * @param {String} file_path must exist
   * @param {String} uptoken 
   * @param {String} user_define_key 
   * @param {String} user_define_mime 
   */
  _common_form_generator(file_path, uptoken, user_define_key = "", user_define_mime = "") {
    let form = new FormData;
    let file_stream = fs.createReadStream(file_path);
    form.append("token", uptoken);
    if (!user_define_mime) {
      form.append("file", file_stream);
    } else {
      form.append("file", file_stream, {
        contentType: user_define_mime
      });
    }
    if (user_define_key) {
      form.append("key", user_define_key)
    }

    return form;
  }

  /**
   * @deprecated
   * @description JS不行||CSS不行||SVG不行||HTML不行||ICON可以(作为一种图片)||WOFF字体可以||json可以||TTF字体可以
   * @returns {Promise<{ok:Boolean,msg:String,data:{link:String}}>}
   * @param {String} file_path 
   */
  upload_hunliji(file_path) {
    return new Promise(async resolve => {
      let o_token = await TokenGetter.get_hunliji();
      if (!o_token.ok) {
        return resolve({
          ok: false,
          msg: `can not get token:${o_token.msg}`
        })
      }
      let form = this._common_form_generator(file_path, o_token.data.uptoken);
      axios.post(this.UPLOAD_QINIU_HOST, form, {
        headers: {
          ...form.getHeaders()
        }
      }).then(axresp => {
        if (axresp.data && axresp.data.image_path) {
          return resolve({
            ok: true,
            msg: "ok",
            data: {
              link: `https://qnm.hunliji.com/${axresp.data.image_path}`
            }
          })
        }
        throw new Error(`no sanity axresp:${util.inspect(axresp.data)}`)
      }).catch(axerr => {
        CommonAxerrHandlerGen(resolve)(axerr);
      })
    })
  }

  /**
   * @returns {Promise<{ok:Boolean,msg:String,data:{link:String}}>}
   * @param {String} file_path 
   */
  upload_owhat(file_path) {
    return new Promise(async resolve => {
      let o_token = await TokenGetter.get_owhat();
      if (!o_token.ok) {
        return resolve({
          ok: false,
          msg: `can not get token:${o_token.msg}`
        })
      }
      let form = this._common_form_generator(file_path, o_token.data.uptoken, o_token.data.key);
      axios.post(this.UPLOAD_QINIU_HOST, form, {
        headers: {
          ...form.getHeaders()
        }
      }).then(axresp => {
        if (axresp.data && axresp.data.key) {
          return resolve({
            ok: true,
            msg: "ok",
            data: {
              link: `https://qimage.owhat.cn/${axresp.data.key}`
            }
          })
        }
        throw new Error(`no sanity axresp:${util.inspect(axresp.data)}`)
      }).catch(axerr => {
        CommonAxerrHandlerGen(resolve)(axerr);
      })
    })
  }

  /**
 * @returns {Promise<{ok:Boolean,msg:String,data:{link:String}}>}
 * @param {String} file_path 
 */
  upload_tuniu(file_path) {
    let tuniuKeyGen = () => `qn/image/${uuid()}${path.extname(file_path)}`;
    return new Promise(async resolve => {
      let o_token = await TokenGetter.get_tuniu();
      if (!o_token.ok) {
        return resolve({
          ok: false,
          msg: `can not get token:${o_token.msg}`
        })
      }
      let form = this._common_form_generator(file_path, o_token.data.uptoken, tuniuKeyGen());
      axios.post(this.UPLOAD_QINIU_HOST, form, {
        headers: {
          ...form.getHeaders()
        },
      }).then(axresp => {
        // debugger
        if (axresp.data && axresp.data.key) {
          return resolve({
            ok: true,
            msg: "ok",
            data: {
              link: `https://s.tuniu.net/${axresp.data.key}`
            }
          })
        }
        throw new Error(`no sanity axresp:${util.inspect(axresp.data)}`)
      }).catch(axerr => {
        CommonAxerrHandlerGen(resolve)(axerr);
      })
    })
  }

  /**
   * @returns {Promise<{ok:Boolean,msg:String,data:{link:String}}>}
   * @param {String} file_path 
   */
  upload_7moor(file_path) {
    const Gen7moorKey = () => {
      let d = new Date;
      let isos = d.toISOString();
      let isos_re = isos.replace("T", "");
      return `im/73859f20-f357-11e6-b43e-3b18b16942dc/${isos_re}/${randomstring.generate(5)}`;
    }
    return new Promise(async resolve => {
      let o_token = await TokenGetter.get_7moor();
      if (!o_token.ok) {
        return resolve({
          ok: false,
          msg: `can not get token:${o_token.msg}`
        })
      }
      let form = this._common_form_generator(file_path, o_token.data.uptoken,
        Gen7moorKey());
      axios.post(this.UPLOAD_QINIU_HOST, form, {
        headers: {
          ...form.getHeaders()
        }
      }).then(axresp => {
        // debugger
        if (axresp.data && axresp.data.key) {
          return resolve({
            ok: true,
            msg: "ok",
            data: {
              link: `http://fs-im-kefu.7moor.com/${axresp.data.key}`
            }
          })
        }
        throw new Error(`no sanity axresp:${util.inspect(axresp.data)}`)
      }).catch(axerr => {
        CommonAxerrHandlerGen(resolve)(axerr);
      })
    })
  }

    /**
   * @returns {Promise<{ok:Boolean,msg:String,data:{link:String}}>}
   * @param {String} file_path 
   */
  upload_udesk(file_path) {
    let udesk_key_gen = () => {
      let ts = Date.now();
      return `${randomstring.generate(parseInt(random_number({ min: 5, max: 10 })))}_${parseInt(ts / 1000)}_${ts % 1000}${path.extname(file_path)}`
    };
    return new Promise(async resolve => {
      let o_token = await TokenGetter.get_udesk();
      if (!o_token.ok) {
        return resolve({
          ok: false,
          msg: `can not get token:${o_token.msg}`
        })
      }
      let form = this._common_form_generator(file_path, o_token.data.uptoken,
        udesk_key_gen());
      axios.post(this.UPLOAD_QINIU_HOST, form, {
        headers: {
          ...form.getHeaders()
        }
      }).then(axresp => {
        // debugger
        if (axresp.data && axresp.data.key) {
          return resolve({
            ok: true,
            msg: "ok",
            data: {
              link: `https://qn-im.udesk.cn/${axresp.data.key}`
            }
          })
        }
        throw new Error(`no sanity axresp:${util.inspect(axresp.data)}`)
      }).catch(axerr => {
        CommonAxerrHandlerGen(resolve)(axerr);
      })
    })
  }

  /**
  * @returns {Promise<{ok:Boolean,msg:String,data:{link:String}}>}
  * @param {String} file_path 
  */
  upload_dú(file_path) {
    let rn = random_number;
    let keyGen = () => `miaohong/post/photo/prod/6566${parseInt(rn({
      min: 200,
      max: 415
    }))}/${(Date.now() * 10000 + parseInt(rn({ min: 1000, max: 5000 }))) / 1E16}E12`
    return new Promise(async resolve => {
      let o_token = await TokenGetter.get_dú();
      if (!o_token.ok) {
        return resolve({
          ok: false,
          msg: `can not get token:${o_token.msg}`
        })
      }
      let form = this._common_form_generator(file_path, o_token.data.uptoken,
        keyGen());
      axios.post(this.UPLOAD_QINIU_HOST, form, {
        headers: {
          ...form.getHeaders()
        }
      }).then(axresp => {
        // debugger
        if (axresp.data && axresp.data.key) {
          return resolve({
            ok: true,
            msg: "ok",
            data: {
              link: `https://du.hupucdn.com/${axresp.data.key}`
            }
          })
        }
        throw new Error(`no sanity axresp:${util.inspect(axresp.data)}`)
      }).catch(axerr => {
        CommonAxerrHandlerGen(resolve)(axerr);
      })
    })
  }

  /**
   * @returns {Promise<{ok:Boolean,msg:String,data:{link:String}}>}
   * @param {String} file_path 
   */
  upload_daovoice(file_path) {
    const Gen7moorKey = () => {
      let d = new Date;
      let isos = d.toISOString();
      let isos_re = isos.replace("T", "");
      return `im/73859f20-f357-11e6-b43e-3b18b16942dc/${isos_re}/${randomstring.generate(5)}`;
    }
    return new Promise(async resolve => {
      let o_token = await TokenGetter.get_daovoice(path.extname(file_path));
      if (!o_token.ok) {
        return resolve({
          ok: false,
          msg: `can not get token:${o_token.msg}`
        })
      }
      let form = this._common_form_generator(file_path, o_token.data.uptoken,
        o_token.data.key);
      axios.post(this.UPLOAD_QINIU_HOST, form, {
        headers: {
          ...form.getHeaders()
        }
      }).then(axresp => {
        // debugger
        if (axresp.data && axresp.data.key) {
          return resolve({
            ok: true,
            msg: "ok",
            data: {
              link: `https://daocom-uploads-cdn.daovoice.io/${axresp.data.key}`
            }
          })
        }
        throw new Error(`no sanity axresp:${util.inspect(axresp.data)}`)
      }).catch(axerr => {
        CommonAxerrHandlerGen(resolve)(axerr);
      })
    })
  }

  /**
   * @deprecated 有可能被删除文件 有待测试; 不支持HTTPS
    * @returns {Promise<{ok:Boolean,msg:String,data:{link:String}}>}
    * @param {String} file_path 
    */
  upload_hiaita(file_path) {
    let key_gen = () => {
      let d = new Date;
      return `pic/${d.getFullYear()}${d.getMonth()}${d.getDate()}/${
        uuid()
        }.gif`
    }
    return new Promise(async resolve => {
      let o_token = await TokenGetter.get_hiaita();
      if (!o_token.ok) {
        return resolve({
          ok: false,
          msg: `can not get token:${o_token.msg}`
        })
      }
      let thekey = key_gen();
      let form = this._common_form_generator(file_path, o_token.data.uptoken,
        thekey);
      axios.post(this.UPLOAD_QINIU_HOST, form, {
        headers: {
          ...form.getHeaders()
        }
      }).then(axresp => {
        // debugger
        if (axresp.data && axresp.data.success) {
          return resolve({
            ok: true,
            msg: "ok",
            data: {
              link: `http://pic.hiaita.com/${thekey}`
            }
          })
        }
        throw new Error(`no sanity axresp:${util.inspect(axresp.data)}`)
      }).catch(axerr => {
        CommonAxerrHandlerGen(resolve)(axerr);
      })
    })
  }



  /**
   * @returns {Promise<{ok:Boolean,msg:String,data:{link:String}}>}
   * @param {String} file_path 
   */
  upload_babytree(file_path) {
    return new Promise(async resolve => {
      let o_token = await TokenGetter.get_babytree();
      if (!o_token.ok) {
        return resolve({
          ok: false,
          msg: `can not get token:${o_token.msg}`
        })
      }
      let form = this._common_form_generator(file_path, o_token.data.uptoken,
      );
      axios.post(this.UPLOAD_QINIU_HOST, form, {
        headers: {
          ...form.getHeaders()
        }
      }).then(axresp => {
        // debugger
        if (axresp.data
          && axresp.data.data
          && axresp.data.data.thumb_info
          && axresp.data.data.thumb_info.big
          && axresp.data.data.thumb_info.big.photo_url
          && util.isString(axresp.data.data.thumb_info.big.photo_url)
          && axresp.data.data.thumb_info.big.photo_url.endsWith("_b.jpg")
        ) {
          let bigurl = axresp.data.data.thumb_info.big.photo_url;
          let indexOf_b = bigurl.indexOf("_b");
          return resolve({
            ok: true,
            msg: "ok",
            data: {
              link: `${bigurl.substr(0, indexOf_b)}`
            }
          })
        }
        throw new Error(`no sanity axresp:${util.inspect(axresp.data)}`)
      }).catch(axerr => {
        CommonAxerrHandlerGen(resolve)(axerr);
      })
    })
  }





}



module.exports = {
  StaticFormUploader: StaticFormUploader
}

